package com.nlp.baidu;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.component.BaiDuAuthService;
import com.enu.ActionTypeEnum;
import com.google.common.collect.Lists;
import com.vo.BDBotSession;
import com.vo.BDClientSession;
import com.vo.BDNLPRequest;
import com.vo.BDNLPResponse;
import com.vo.BDQueryInfo;
import com.vo.BDRequest;

/*
 * unit对话服务
 */
public class UnitService {
    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
	private static final Logger LOG = LoggerFactory.getLogger(UnitService.class);
	
	/**
	 * 
	 * @Title: utterance   
	 * @Description: 发请求给bot识别
	 * @author: knight.lu
	 * @param: @param botId  机器人(技能)id
	 * @param: @param sessionId 每一次完成的对话id,由response获取
	 * @param: @param userId 标记唯一用户
	 * @param: @param logId  每一句对话id,方便后台管理
	 * @param: @param queryText 要对话的文字
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
    public static BDNLPResponse utterance(String botId, String sessionId, String userId, String logId, String queryText) {
        // 请求URL
    	BDNLPResponse response = new BDNLPResponse();
        try {
            // 请求参数
            //sString params = "{\"bot_session\":\"\",\"log_id\":\"18078\",\"request\":{\"bernard_level\":1,\"client_session\":\"{\\\"client_results\\\":\\\"\\\", \\\"candidate_options\\\":[]}\",\"query\":\""+txt+"\",\"query_info\":{\"asr_candidates\":[],\"source\":\"KEYBOARD\",\"type\":\"TEXT\"},\"updates\":\"\",\"user_id\":\"88888\"},\"bot_id\":\"18078\",\"version\":\"2.0\"}";
        	BDNLPRequest nlpRequest =  build(botId,sessionId, userId, logId,queryText);
        	String accessToken = BaiDuAuthService.getAuth();
        	String requestText = JSONObject.toJSONString(nlpRequest);
        	LOG.info("nlp request: " + requestText);
            String returnResult = HttpUtil.post(BaiDuAuthService.TALK_URL, accessToken, "application/json", requestText);
            LOG.info("nlp result: " + returnResult);
            JSONObject json = JSON.parseObject(returnResult);
            response.setBotId(botId);
            response.setLogId(logId);
            int responseCode = json.getInteger("error_code");
            if(responseCode != 0) {
            	LOG.error("请求NLP错误:{}",json.getString("error_msg"));
            	response.setSay(BaiDuAuthService.BOT_ERROR);
            	response.setActionType(ActionTypeEnum.FAILTURE);
            	response.setSessionId(null);
            	return response;
            }
            JSONObject result = json.getJSONObject("result");
            JSONObject bot_session = JSONObject.parseObject(result.getString("bot_session"));
            String bot_sessionId = bot_session.getString("session_id");
            JSONObject bot_response = result.getJSONObject("response");
            JSONArray action_list = bot_response.getJSONArray("action_list");
            JSONObject answerAction = action_list.getJSONObject(0);
            String say = answerAction.getString("say");
            if(action_list.size() > 1) {
            	JSONObject askAction = action_list.getJSONObject(1);
            	String ask = askAction.getString("say");
            	response.setAsk(ask);
            }
            String type = answerAction.getString("type");
            response.setActionType(ActionTypeEnum.getActionTypeEnum(type));
            response.setSay(say);
            response.setSessionId(bot_sessionId);
            
            JSONObject schema = bot_response.getJSONObject("schema");
            JSONArray intents = schema.getJSONArray("slots");
            if(intents != null) {
            	intents.forEach(x->{
            		JSONObject intent = JSONObject.parseObject(x.toString());
            		Map<String,String> slots = response.getMatchSlot();
            		slots.put(intent.getString("name"), intent.getString("normalized_word"));
            	});
            }
           LOG.info("result: " + JSONObject.toJSONString(response));
           return response;
        } catch (Exception e) {
            LOG.error("请求NLP错误",e);
            response.setActionType(ActionTypeEnum.BOT_ERROR);
            response.setSay(BaiDuAuthService.BOT_ERROR);
            return response;
        }
    }
    
    private static BDNLPRequest build(String botId, String sessionId, String userId, String logId, String queryText) {
    	BDNLPRequest nlp = new BDNLPRequest();
    	nlp.setBot_session("");
    	nlp.setLog_id(logId);
    	nlp.setBot_id(botId);
    	nlp.setVersion("2.0");
    	
    	BDClientSession clientSession = new BDClientSession();
    	clientSession.setClient_results("");
    	clientSession.setCandidate_options(Lists.newArrayList());
    	
    	BDQueryInfo query = new BDQueryInfo();
    	query.setAsr_candidates(Lists.newArrayList());
    	query.setSource("KEYBOARD");
    	query.setType("TEXT");
    	
    	BDRequest request = new BDRequest();
    	request.setQuery(queryText);
    	request.setBernard_level(1);
    	request.setQuery_info(query);
    	request.setUpdates("");
    	request.setUser_id(userId);
    	request.setClient_session(JSONObject.toJSONString(clientSession));
    	request.setQuery_info(query);
    	if(!StringUtils.isEmpty(sessionId)) {
    		BDBotSession serverSession = new BDBotSession();
    		serverSession.setSession_id(sessionId);
    		nlp.setBot_session(JSONObject.toJSONString(serverSession));
    	}
    	
    	nlp.setRequest(request);
    	return nlp;
    }
}
